import type { VbenFormSchema } from '#/adapter/form';

import type {
  OnActionClickParams,
  VxeTableGridOptions,
} from '#/adapter/vxe-table';
import type { BOMApi } from '#/models/bom/bom';
import type { Recordable } from '@vben/types';

import { z } from '#/adapter/form';
import { dictFormatter, useDictOptions } from '#/hooks/useDictOptions';
import { $t } from '#/locales';
import { DICT_TYPE } from '#/utils/dict';
import { op } from '#/utils/permission';
import { SystemUserModel } from '#/models/system/user';



/**
 * 单位选项
 */
export const UNIT_OPTIONS = [
  { label: '个', value: '个' },
  { label: '件', value: '件' },
  { label: '套', value: '套' },
  { label: '千克', value: 'kg' },
  { label: '克', value: 'g' },
  { label: '米', value: 'm' },
  { label: '厘米', value: 'cm' },
  { label: '毫米', value: 'mm' },
  { label: '升', value: 'L' },
  { label: '毫升', value: 'mL' },
];

/**
 * 表格列配置
 * @description 使用函数的形式返回列数据而不是直接export一个Array常量，是为了响应语言切换时重新翻译表头
 * @param onActionClick 表格操作按钮点击事件
 */
export function useColumns(
  onActionClick?: (params: OnActionClickParams<BOMApi.BOM>) => void,
): VxeTableGridOptions<BOMApi.BOM>['columns'] {
  return [
    {
      type: 'checkbox',
      width: 50,
    },
    {
      type: 'seq',
      title: '序',
      width: 60,
      align: 'center',
      visible: true,
    },
    {
      field: 'id',
      title: 'ID',
      width: 80,
    },
    {
      field: 'bom_code',
      title: 'BOM编码',
      width: 150,
      align: 'left',
      showOverflow: 'tooltip',
    },
    {
      field: 'product_name',
      title: '产品',
      width: 180,
      align: 'left',
      showOverflow: 'tooltip',
    },
    {
      field: 'product_sku',
      title: '产品SKU',
      width: 150,
      align: 'left',
      showOverflow: 'tooltip',
    },
    {
      field: 'bom_type',
      title: 'BOM类型',
      width: 120,
      align: 'center',
      showOverflow: 'tooltip',
      formatter: dictFormatter(DICT_TYPE.BOM_TYPE),
    },
    {
      field: 'version',
      title: '版本',
      width: 80,
      align: 'center',
    },
    {
      field: 'status',
      title: '状态',
      width: 100,
      align: 'center',
      showOverflow: 'tooltip',
      formatter: dictFormatter(DICT_TYPE.BOM_STATUS),
    },
    {
      field: 'lifecycle_status',
      title: '生命周期',
      width: 120,
      align: 'center',
      showOverflow: 'tooltip',
      formatter: dictFormatter(DICT_TYPE.LIFECYCLE_STATUS),
    },
    {
      field: 'effective_date',
      title: '生效日期',
      width: 120,
      align: 'center',
    },
    {
      field: 'expiry_date',
      title: '失效日期',
      width: 120,
      align: 'center',
    },
    {
      field: 'creator',
      title: '创建人',
      width: 100,
      align: 'center',
    },
    {
      field: 'create_time',
      title: '创建时间',
      width: 150,
      align: 'center',
    },
    {
      align: 'center',
      cellRender: {
        attrs: {
          nameField: 'bom_code',
          nameTitle: $t('bom.bom.title'),
          onClick: onActionClick,
        },
        name: 'CellOperation',
        options: [
          op('bom:bom:view', 'view'),
          op('bom:bom:edit', 'edit'),
          op('bom:bom:delete', 'delete'),
        ],
      },
      field: 'action',
      fixed: 'right',
      title: '操作',
      width: 180,
      visible: true,
    },
  ];
}

/**
 * 搜索表单配置
 * @description 用于BOM列表页的搜索表单字段配置
 */
export function useGridFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'bom_code',
      label: 'BOM编码',
      component: 'Input',
      componentProps: {
        placeholder: '请输入BOM编码',
        allowClear: true,
      },
    },
    {
      fieldName: 'product_name',
      label: '产品名称',
      component: 'Input',
      componentProps: {
        placeholder: '请输入产品名称',
        allowClear: true,
      },
    },
    {
      fieldName: 'product_sku',
      label: '产品SKU',
      component: 'Input',
      componentProps: {
        placeholder: '请输入产品SKU',
        allowClear: true,
      },
    },
    {
      fieldName: 'bom_type',
      label: 'BOM类型',
      component: 'Select',
      componentProps: {
        placeholder: '请选择BOM类型',
        allowClear: true,
        options: useDictOptions(DICT_TYPE.BOM_TYPE),
      },
    },
    {
      fieldName: 'status',
      label: '状态',
      component: 'Select',
      componentProps: {
        placeholder: '请选择状态',
        allowClear: true,
        options: useDictOptions(DICT_TYPE.BOM_STATUS),
      },
    },
    {
      fieldName: 'lifecycle_status',
      label: '生命周期',
      component: 'Select',
      componentProps: {
        placeholder: '请选择生命周期状态',
        allowClear: true,
        options: useDictOptions(DICT_TYPE.LIFECYCLE_STATUS),
      },
    },
    {
      fieldName: 'effective_date',
      label: '生效日期',
      component: 'RangePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        placeholder: ['开始日期', '结束日期'],
      },
    },
  ];
}

/**
 * 创建和编辑表单配置
 * @description 用于BOM创建和编辑表单的字段配置，应用于 form.vue 组件
 */
export function useSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'bom_id',
      label: 'BOM ID',
      component: 'Input',
      componentProps: {
        style: { display: 'none' }, // 隐藏字段
      },
    },
    {
      fieldName: 'product',
      label: '产品',
      component: 'ApiSelect',
      componentProps: {
        api: async (keyword: string) => {
          try {
            const m = await import('#/api/product/product');
            const result = await m.searchProducts(keyword || '');
            return result;
          } catch (error) {
            console.error('加载产品API时出错:', error);
            return Promise.resolve([]);
          }
        },
        params: {
          search: '', // 初始搜索参数
        },
        onSearch: (value: string) => {
          // 确保返回正确格式的搜索参数
          return { search: value };
        },
        filterOption: (input: string, option: any) => {
          // 本地过滤选项，确保搜索结果准确
          return option?.display_name?.toLowerCase().includes(input.toLowerCase()) ||
                 option?.sku?.toLowerCase().includes(input.toLowerCase()) ||
                 option?.name?.toLowerCase().includes(input.toLowerCase());
        },
        resultField: '', // 直接返回数组，不需要嵌套字段
        labelField: 'display_name',
        valueField: 'product_id',
        placeholder: '请输入产品名称或SKU搜索',
        showSearch: true,
        allowClear: true,
        class: 'w-96',
      },
      rules: z
        .string()
        .min(1, $t('ui.formRules.required', ['产品']))
        .max(50, $t('ui.formRules.maxLength', ['产品', 50])),
    },
    {
      fieldName: 'bom_code',
      label: 'BOM编码',
      component: 'Input',
      componentProps: ({ formModel }) => {
        try {
          // 安全地检查formModel和bom_id是否存在
          const hasBomId = formModel && formModel.bom_id;
          return {
            placeholder: hasBomId ? '请输入BOM编码' : '自动生成',
            maxlength: 50,
            readonly: !hasBomId, // 新增模式下只读，编辑模式下可编辑
            addonAfter: hasBomId ? '' : '自动生成',
            class: 'w-96', // 使用Tailwind CSS类设置宽度 (w-64 = 16rem = 256px)
          };
        } catch (error) {
          console.error('获取BOM编码字段属性时出错:', error);
          return {
            placeholder: '请输入BOM编码',
            maxlength: 50,
            readonly: false,
            addonAfter: '',
            class: 'w-96', // 使用Tailwind CSS类设置宽度 (w-64 = 16rem = 256px)
          };
        }
      },
      rules: z
        .string()
        .min(1, $t('ui.formRules.required', ['BOM编码']))
        .max(50, $t('ui.formRules.maxLength', ['BOM编码', 50]))
        .regex(/^[A-Z0-9-_]+$/, 'BOM编码只能包含大写字母、数字、连字符和下划线'),
      dependencies: {
        triggerFields: ['bom_id'],
      },
    },
    {
      fieldName: 'version',
      label: '版本',
      component: 'Input',
      defaultValue: '1.0',
      componentProps: {
        placeholder: '请输入版本号',
        maxlength: 20,
        class: 'w-32', // 使用Tailwind CSS类设置宽度 (w-48 = 12rem = 192px)
      },
      rules: z
        .string()
        .min(1, $t('ui.formRules.required', ['版本号']))
        .max(20, $t('ui.formRules.maxLength', ['版本号', 20])),
    },
    {
      fieldName: 'bom_type',
      label: 'BOM类型',
      component: 'Select',
      defaultValue: 'production',
      componentProps: {
        placeholder: '请选择BOM类型',
        options: useDictOptions(DICT_TYPE.BOM_TYPE),
        class: 'w-48'
      },
      rules: 'selectRequired',
    },
    {
      fieldName: 'status',
      label: '状态',
      component: 'Select',
      defaultValue: 'draft',
      componentProps: {
        placeholder: '请选择状态',
        options: useDictOptions(DICT_TYPE.BOM_STATUS),
        class: 'w-48'
      },
      rules: 'selectRequired',
    },
    {
      fieldName: 'lifecycle_status',
      label: '生命周期状态',
      component: 'Select',
      defaultValue: 'development',
      componentProps: {
        placeholder: '请选择生命周期状态',
        options: useDictOptions(DICT_TYPE.LIFECYCLE_STATUS),
        class: 'w-48'
      },
      rules: 'selectRequired',
    },
    {
      fieldName: 'effective_date',
      label: '生效日期',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        placeholder: '请选择生效日期',
      },
    },
    {
      fieldName: 'expiry_date',
      label: '失效日期',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        placeholder: '请选择失效日期',
      },
    },
    {
      fieldName: 'description',
      label: '描述',
      component: 'Textarea',
      componentProps: {
        placeholder: '请输入BOM描述',
        rows: 3,
        maxlength: 500,
        showCount: true,
        class: 'w-full',
      },
    },
    {
      fieldName: 'remark',
      label: '备注',
      component: 'Textarea',
      componentProps: {
        placeholder: '请输入备注信息',
        rows: 2,
        maxlength: 256,
        showCount: true,
        class: 'w-full',
      },
    },
  ];
}

/**
 * BOM组件表单配置
 * @description 用于BOM组件创建和编辑表单的字段配置
 */
export function useComponentSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'material',
      label: '物料',
      component: 'ApiSelect',
      componentProps: {
        api: () => import('#/api/bom/bom').then((m) => m.getMaterials()),
        resultField: 'items',
        labelField: 'name',
        valueField: 'id',
        placeholder: '请选择物料',
        showSearch: true,
        filterOption: (input: string, option: any) => {
          return option.label.toLowerCase().includes(input.toLowerCase());
        },
      },
    },
    {
      fieldName: 'quantity',
      label: '数量',
      component: 'InputNumber',
      componentProps: {
        placeholder: '请输入数量',
        min: 0,
        precision: 4,
        style: { width: '100%' },
      },
    },
    {
      fieldName: 'material_type',
      label: '物料类型',
      component: 'Select',
      componentProps: {
        options: useDictOptions(DICT_TYPE.MATERIAL_TYPE),
        placeholder: '请选择物料类型',
      },
    },
    {
      fieldName: 'unit',
      label: '单位',
      component: 'Select',
      componentProps: {
        options: UNIT_OPTIONS,
        placeholder: '请选择单位',
      },
    },
    {
      fieldName: 'operation_code',
      label: '工序编码',
      component: 'Input',
      componentProps: {
        placeholder: '请输入工序编码',
        maxlength: 50,
      },
    },
    {
      fieldName: 'workstation',
      label: '工位',
      component: 'Input',
      componentProps: {
        placeholder: '请输入工位',
        maxlength: 100,
      },
    },
    {
      fieldName: 'is_optional',
      label: '是否可选',
      component: 'Switch',
      defaultValue: false,
    },
    {
      fieldName: 'scrap_rate',
      label: '报废率(%)',
      component: 'InputNumber',
      componentProps: {
        placeholder: '请输入报废率',
        min: 0,
        max: 100,
        precision: 2,
        style: { width: '100%' },
      },
    },
    {
      fieldName: 'unit_cost',
      label: '单位成本',
      component: 'InputNumber',
      componentProps: {
        placeholder: '请输入单位成本',
        min: 0,
        precision: 4,
        style: { width: '100%' },
      },
    },
    {
      fieldName: 'preferred_supplier',
      label: '首选供应商',
      component: 'ApiSelect',
      componentProps: {
        // TODO: 实现供应商API后替换为正确的API调用
        options: [
          { label: '供应商A', value: 1 },
          { label: '供应商B', value: 2 },
          { label: '供应商C', value: 3 },
        ],
        placeholder: '请选择供应商',
        showSearch: true,
        allowClear: true,
      },
    },
    {
      fieldName: 'remark',
      label: '备注',
      component: 'InputTextArea',
      componentProps: {
        placeholder: '请输入备注信息',
        rows: 2,
        maxlength: 256,
        showCount: true,
      },
    },
  ];
}

/**
 * 文档表单配置
 * @description 用于BOM文档创建和编辑表单的字段配置
 */
export function useDocumentSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'title',
      label: '文档标题',
      component: 'Input',
      componentProps: {
        placeholder: '请输入文档标题',
        maxlength: 100,
      },
      rules: z
        .string()
        .min(1, $t('ui.formRules.required', ['文档标题']))
        .max(100, $t('ui.formRules.maxLength', ['文档标题', 100])),
    },
    {
      fieldName: 'type',
      label: '文档类型',
      component: 'Select',
      componentProps: {
        placeholder: '请选择文档类型',
        options: useDictOptions(DICT_TYPE.DOCUMENT_TYPE),
      },
      rules: 'selectRequired',
    },
    {
      fieldName: 'file',
      label: '文档文件',
      component: 'Upload',
      componentProps: {
        accept: '.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.jpg,.jpeg,.png',
        maxCount: 1,
        maxSize: 10 * 1024 * 1024, // 10MB
      },
      rules: 'required',
    },
    {
      fieldName: 'version',
      label: '文档版本',
      component: 'Input',
      defaultValue: '1.0',
      componentProps: {
        placeholder: '请输入文档版本',
        maxlength: 20,
      },
    },
    {
      fieldName: 'status',
      label: '状态',
      component: 'Select',
      defaultValue: 'draft',
      componentProps: {
        placeholder: '请选择状态',
        options: useDictOptions(DICT_TYPE.BOM_STATUS),
      },
      rules: 'selectRequired',
    },
    {
      fieldName: 'effective_date',
      label: '生效日期',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        placeholder: '请选择生效日期',
      },
    },
    {
      fieldName: 'expiry_date',
      label: '失效日期',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        placeholder: '请选择失效日期',
      },
    },
    {
      fieldName: 'description',
      label: '描述',
      component: 'InputTextArea',
      componentProps: {
        placeholder: '请输入文档描述',
        rows: 3,
        maxlength: 500,
        showCount: true,
      },
    },
    {
      fieldName: 'remark',
      label: '备注',
      component: 'InputTextArea',
      componentProps: {
        placeholder: '请输入备注信息',
        rows: 2,
        maxlength: 256,
        showCount: true,
      },
    },
  ];
}

/**
 * 替代物料表单配置
 * @description 用于BOM替代物料创建和编辑表单的字段配置
 */
export function useAlternativeSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'component_material',
      label: '组件物料',
      component: 'ApiSelect',
      componentProps: {
        api: () => import('#/api/bom/bom').then((m) => m.getMaterials()),
        resultField: 'items',
        labelField: 'name',
        valueField: 'id',
        placeholder: '请选择组件物料',
        showSearch: true,
        filterOption: (input: string, option: any) => {
          return option.label.toLowerCase().includes(input.toLowerCase());
        },
      },
    },
    {
      fieldName: 'alternative_material',
      label: '替代物料',
      component: 'ApiSelect',
      componentProps: {
        api: () => import('#/api/bom/bom').then((m) => m.getMaterials()),
        resultField: 'items',
        labelField: 'name',
        valueField: 'id',
        placeholder: '请选择替代物料',
        showSearch: true,
        filterOption: (input: string, option: any) => {
          return option.label.toLowerCase().includes(input.toLowerCase());
        },
      },
    },
    {
      fieldName: 'alternative_rate',
      label: '替代比例(%)',
      component: 'InputNumber',
      defaultValue: 100,
      componentProps: {
        placeholder: '请输入替代比例',
        min: 0,
        max: 100,
        precision: 2,
        style: { width: '100%' },
      },
    },
    {
      fieldName: 'approval_status',
      label: '审批状态',
      component: 'Select',
      defaultValue: 'pending',
      componentProps: {
        placeholder: '请选择审批状态',
        options: useDictOptions(DICT_TYPE.APPROVAL_STATUS),
      },
      rules: 'selectRequired',
    },
    {
      fieldName: 'effective_date',
      label: '生效日期',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        placeholder: '请选择生效日期',
      },
    },
    {
      fieldName: 'expiry_date',
      label: '失效日期',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        placeholder: '请选择失效日期',
      },
    },
    {
      fieldName: 'remark',
      label: '备注',
      component: 'InputTextArea',
      componentProps: {
        placeholder: '请输入备注信息',
        rows: 2,
        maxlength: 256,
        showCount: true,
      },
    },
  ];
}



/**
 * 版本历史表单配置
 * @description 用于BOM版本历史创建和编辑表单的字段配置
 */
export function useVersionSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'version',
      label: '版本号',
      component: 'Input',
      componentProps: {
        placeholder: '请输入版本号',
        maxlength: 20,
      },
      rules: z
        .string()
        .min(1, $t('ui.formRules.required', ['版本号']))
        .max(20, $t('ui.formRules.maxLength', ['版本号', 20])),
    },
    {
      fieldName: 'change_type',
      label: '变更类型',
      component: 'Select',
      componentProps: {
        placeholder: '请选择变更类型',
        options: useDictOptions(DICT_TYPE.CHANGE_TYPE),
      },
      rules: 'selectRequired',
    },
    {
      fieldName: 'change_description',
      label: '变更描述',
      component: 'InputTextArea',
      componentProps: {
        placeholder: '请输入变更描述',
        rows: 3,
        maxlength: 500,
        showCount: true,
      },
      rules: z
        .string()
        .min(1, $t('ui.formRules.required', ['变更描述']))
        .max(500, $t('ui.formRules.maxLength', ['变更描述', 500])),
    },
    {
      fieldName: 'effective_date',
      label: '生效日期',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        placeholder: '请选择生效日期',
      },
      rules: 'required',
    },
    {
      fieldName: 'approver',
      label: '审批人',
      component: 'ApiSelect',
      componentProps: () => {
        const userModel = new SystemUserModel();
        return {
          api: (params: Recordable<any>) => userModel.list(params),
          resultField: 'items',
          labelField: 'nickname',
          valueField: 'id',
          placeholder: '请选择审批人',
          showSearch: true,
          filterOption: (input: string, option: any) => {
            return option.label.toLowerCase().includes(input.toLowerCase());
          },
        };
      },
    },
    {
      fieldName: 'approval_status',
      label: '审批状态',
      component: 'Select',
      defaultValue: 'pending',
      componentProps: {
        placeholder: '请选择审批状态',
        options: useDictOptions(DICT_TYPE.APPROVAL_STATUS),
      },
      rules: 'selectRequired',
    },
    {
      fieldName: 'approval_date',
      label: '审批日期',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        placeholder: '请选择审批日期',
      },
    },
    {
      fieldName: 'remark',
      label: '备注',
      component: 'InputTextArea',
      componentProps: {
        placeholder: '请输入备注信息',
        rows: 2,
        maxlength: 256,
        showCount: true,
      },
    },
  ];
}

// 表单验证规则
export const bomFormRules = {
  product: [
    {
      required: true,
      message: '请选择产品',
      trigger: 'change',
    },
  ],
  bom_code: [
    {
      required: true,
      message: '请输入BOM编码',
      trigger: 'blur',
    },
    {
      max: 50,
      message: 'BOM编码长度不能超过50个字符',
      trigger: 'blur',
    },
  ],
  version: [
    {
      required: true,
      message: '请输入版本号',
      trigger: 'blur',
    },
  ],
  bom_type: [
    {
      required: true,
      message: '请选择BOM类型',
      trigger: 'change',
    },
  ],
  status: [
    {
      required: true,
      message: '请选择状态',
      trigger: 'change',
    },
  ],
  lifecycle_status: [
    {
      required: true,
      message: '请选择生命周期状态',
      trigger: 'change',
    },
  ],
};

// BOM组件表单验证规则
export const componentFormRules = {
  material: [
    {
      required: true,
      message: '请选择物料',
      trigger: 'change',
    },
  ],
  quantity: [
    {
      required: true,
      message: '请输入数量',
      trigger: 'blur',
    },
    {
      type: 'number',
      min: 0,
      message: '数量必须大于0',
      trigger: 'blur',
    },
  ],
  material_type: [
    {
      required: true,
      message: '请选择物料类型',
      trigger: 'change',
    },
  ],
  unit: [
    {
      required: true,
      message: '请输入单位',
      trigger: 'blur',
    },
  ],
};

// 替代物料表单验证规则
export const alternativeFormRules = {
  component_material: [
    {
      required: true,
      message: '请选择组件物料',
      trigger: 'change',
    },
  ],
  alternative_material: [
    {
      required: true,
      message: '请选择替代物料',
      trigger: 'change',
    },
  ],
  alternative_rate: [
    {
      required: true,
      message: '请输入替代率',
      trigger: 'blur',
    },
    {
      type: 'number',
      min: 0,
      max: 100,
      message: '替代率必须在0-100之间',
      trigger: 'blur',
    },
  ],
  approval_status: [
    {
      required: true,
      message: '请选择审批状态',
      trigger: 'change',
    },
  ],
};

// 文档表单验证规则
export const documentFormRules = {
  title: [
    {
      required: true,
      message: '请输入文档标题',
      trigger: 'blur',
    },
    {
      max: 200,
      message: '文档标题长度不能超过200个字符',
      trigger: 'blur',
    },
  ],
  type: [
    {
      required: true,
      message: '请选择文档类型',
      trigger: 'change',
    },
  ],
  file: [
    {
      required: true,
      message: '请选择文件',
      trigger: 'change',
    },
  ],
  status: [
    {
      required: true,
      message: '请选择状态',
      trigger: 'change',
    },
  ],
};

// 版本历史表单验证规则
export const versionFormRules = {
  version: [
    {
      required: true,
      message: '请输入版本号',
      trigger: 'blur',
    },
    {
      max: 20,
      message: '版本号长度不能超过20个字符',
      trigger: 'blur',
    },
  ],
  change_type: [
    {
      required: true,
      message: '请选择变更类型',
      trigger: 'change',
    },
  ],
  change_description: [
    {
      required: true,
      message: '请输入变更描述',
      trigger: 'blur',
    },
    {
      max: 500,
      message: '变更描述长度不能超过500个字符',
      trigger: 'blur',
    },
  ],
  effective_date: [
    {
      required: true,
      message: '请选择生效日期',
      trigger: 'change',
    },
  ],
  approval_status: [
    {
      required: true,
      message: '请选择审批状态',
      trigger: 'change',
    },
  ],
};

// 表单默认值
export const bomFormDefaultValues = {
  product: null,
  bom_code: '',
  version: '1.0',
  bom_type: 'production',
  status: 'draft',
  lifecycle_status: 'development',
  effective_date: null,
  expiry_date: null,
  description: '',
  remark: '',
};

// BOM组件表单默认值
export const componentFormDefaultValues = {
  material: null,
  quantity: 1,
  material_type: '',
  unit: '',
  operation_code: '',
  workstation: '',
  is_optional: false,
  scrap_rate: 0,
  unit_cost: 0,
  preferred_supplier: null,
  remark: '',
};

// 替代物料表单默认值
export const alternativeFormDefaultValues = {
  component_material: null,
  alternative_material: null,
  alternative_rate: 100,
  approval_status: 'pending',
  effective_date: null,
  expiry_date: null,
  remark: '',
};

// 文档表单默认值
export const documentFormDefaultValues = {
  title: '',
  type: '',
  file: null,
  version: '1.0',
  status: 'draft',
  effective_date: null,
  expiry_date: null,
  description: '',
  remark: '',
};

// 版本历史表单默认值
export const versionFormDefaultValues = {
  version: '',
  change_type: '',
  change_description: '',
  effective_date: null,
  approver: null,
  approval_status: 'pending',
  approval_date: null,
  remark: '',
};



/**
 * 导出所有BOM模块配置
 * @description 汇总所有BOM模块相关的配置，方便在组件中使用
 */



/**
 * 获取选项卡配置
 * @description 使用函数的形式返回选项卡配置而不是直接export一个Array常量
 */
export function useTabbedSchema() {
  return [
    {
      key: 'basic',
      label: '基本信息',
      fields: [
        'product',
        'bom_code',
        'version',
        'bom_type',
        'status',
        'lifecycle_status',
        'effective_date',
        'expiry_date',
        'description',
        'remark',
      ],
    },
    {
      key: 'components',
      label: 'BOM组件',
      fields: [],
    },
    {
      key: 'alternatives',
      label: '替代物料',
      fields: [],
    },
    {
      key: 'documents',
      label: '文档',
      fields: [],
    },
    {
      key: 'versions',
      label: '版本历史',
      fields: [],
    },
  ];
}

/**
 * BOM组件表格列配置
 * @description 使用函数的形式返回列数据而不是直接export一个Array常量，是为了响应语言切换时重新翻译表头
 * @param onActionClick 表格操作按钮点击事件
 */
export function useComponentColumns(
  onActionClick?: (params: OnActionClickParams<BOMApi.BOMComponent>) => void,
): VxeTableGridOptions<BOMApi.BOMComponent>['columns'] {
  return [
    {
      type: 'checkbox',
      width: 50,
    },
    {
      type: 'seq',
      title: '序',
      width: 60,
      align: 'center',
      visible: true,
    },
    {
      field: 'id',
      title: 'ID',
      width: 80,
    },
    {
      field: 'material_code',
      title: '物料编码',
      width: 120,
      align: 'left',
      showOverflow: 'tooltip',
    },
    {
      field: 'material_name',
      title: '物料名称',
      width: 180,
      align: 'left',
      showOverflow: 'tooltip',
    },
    {
      field: 'material_specification',
      title: '规格型号',
      width: 150,
      align: 'left',
      showOverflow: 'tooltip',
    },
    {
      field: 'material_type',
      title: '物料类型',
      width: 120,
      align: 'center',
      showOverflow: 'tooltip',
      formatter: dictFormatter(DICT_TYPE.MATERIAL_TYPE),
    },
    {
      field: 'quantity',
      title: '数量',
      width: 100,
      align: 'right',
    },
    {
      field: 'unit',
      title: '单位',
      width: 80,
      align: 'center',
    },
    {
      field: 'operation_code',
      title: '工序编码',
      width: 120,
      align: 'left',
      showOverflow: 'tooltip',
    },
    {
      field: 'workstation',
      title: '工位',
      width: 120,
      align: 'left',
      showOverflow: 'tooltip',
    },
    {
      field: 'is_optional',
      title: '是否可选',
      width: 100,
      align: 'center',
      formatter: ({ cellValue }) => (cellValue ? '是' : '否'),
    },
    {
      field: 'scrap_rate',
      title: '报废率(%)',
      width: 100,
      align: 'right',
    },
    {
      field: 'unit_cost',
      title: '单位成本',
      width: 100,
      align: 'right',
    },
    {
      field: 'preferred_supplier_name',
      title: '首选供应商',
      width: 150,
      align: 'left',
      showOverflow: 'tooltip',
    },
    {
      field: 'remark',
      title: '备注',
      width: 150,
      align: 'left',
      showOverflow: 'tooltip',
    },
    {
      align: 'center',
      cellRender: {
        attrs: {
          nameField: 'material_name',
          nameTitle: 'BOM组件',
          onClick: onActionClick,
        },
        name: 'CellOperation',
        options: [
          op('bom:bom:component:view', 'view'),
          op('bom:bom:component:edit', 'edit'),
          op('bom:bom:component:delete', 'delete'),
        ],
      },
      field: 'action',
      fixed: 'right',
      title: '操作',
      width: 150,
      visible: true,
    },
  ];
}

/**
 * 替代物料表格列配置
 * @description 使用函数的形式返回列数据而不是直接export一个Array常量，是为了响应语言切换时重新翻译表头
 * @param onActionClick 表格操作按钮点击事件
 */
export function useAlternativeColumns(
  onActionClick?: (
    params: OnActionClickParams<BOMApi.AlternativeMaterial>,
  ) => void,
): VxeTableGridOptions<BOMApi.AlternativeMaterial>['columns'] {
  return [
    {
      type: 'checkbox',
      width: 50,
    },
    {
      type: 'seq',
      title: '序',
      width: 60,
      align: 'center',
      visible: true,
    },
    {
      field: 'id',
      title: 'ID',
      width: 80,
    },
    {
      field: 'alternative_material_code',
      title: '物料编码',
      width: 120,
      align: 'left',
      showOverflow: 'tooltip',
    },
    {
      field: 'alternative_material_name',
      title: '物料名称',
      width: 180,
      align: 'left',
      showOverflow: 'tooltip',
    },
    {
      field: 'alternative_material_specification',
      title: '规格型号',
      width: 150,
      align: 'left',
      showOverflow: 'tooltip',
    },
    {
      field: 'alternative_rate',
      title: '替代比例(%)',
      width: 120,
      align: 'right',
    },
    {
      field: 'approval_status',
      title: '审批状态',
      width: 120,
      align: 'center',
      formatter: dictFormatter(DICT_TYPE.APPROVAL_STATUS),
    },
    {
      field: 'effective_date',
      title: '生效日期',
      width: 120,
      align: 'center',
    },
    {
      field: 'expiry_date',
      title: '失效日期',
      width: 120,
      align: 'center',
    },
    {
      field: 'remark',
      title: '备注',
      width: 150,
      align: 'left',
      showOverflow: 'tooltip',
    },
    {
      align: 'center',
      cellRender: {
        attrs: {
          nameField: 'alternative_material_name',
          nameTitle: '替代物料',
          onClick: onActionClick,
        },
        name: 'CellOperation',
        options: [
          op('bom:bom:alternative:view', 'view'),
          op('bom:bom:alternative:edit', 'edit'),
          op('bom:bom:alternative:delete', 'delete'),
        ],
      },
      field: 'action',
      fixed: 'right',
      title: '操作',
      width: 150,
      visible: true,
    },
  ];
}

/**
 * 文档表格列配置
 * @description 使用函数的形式返回列数据而不是直接export一个Array常量，是为了响应语言切换时重新翻译表头
 * @param onActionClick 表格操作按钮点击事件
 */
export function useDocumentColumns(
  onActionClick?: (params: OnActionClickParams<BOMApi.BOMDocument>) => void,
): VxeTableGridOptions<BOMApi.BOMDocument>['columns'] {
  return [
    {
      type: 'checkbox',
      width: 50,
    },
    {
      type: 'seq',
      title: '序',
      width: 60,
      align: 'center',
      visible: true,
    },
    {
      field: 'id',
      title: 'ID',
      width: 80,
    },
    {
      field: 'document_name',
      title: '文档名称',
      width: 200,
      align: 'left',
      showOverflow: 'tooltip',
    },
    {
      field: 'type',
      title: '文档类型',
      width: 120,
      align: 'center',
      formatter: dictFormatter(DICT_TYPE.DOCUMENT_TYPE),
    },
    {
      field: 'file_size',
      title: '文件大小',
      width: 100,
      align: 'right',
      formatter: ({ cellValue }) => {
        if (!cellValue) return '-';
        const size = Number(cellValue);
        if (size < 1024) return `${size} B`;
        if (size < 1024 * 1024) return `${(size / 1024).toFixed(2)} KB`;
        return `${(size / (1024 * 1024)).toFixed(2)} MB`;
      },
    },
    {
      field: 'uploaded_by',
      title: '上传人',
      width: 100,
      align: 'center',
    },
    {
      field: 'upload_time',
      title: '上传时间',
      width: 150,
      align: 'center',
    },
    {
      field: 'remark',
      title: '备注',
      width: 150,
      align: 'left',
      showOverflow: 'tooltip',
    },
    {
      align: 'center',
      cellRender: {
        attrs: {
          nameField: 'document_name',
          nameTitle: 'BOM文档',
          onClick: onActionClick,
        },
        name: 'CellOperation',
        options: [
          op('bom:bom:document:view', 'view'),
          op('bom:bom:document:download', 'download'),
          op('bom:bom:document:delete', 'delete'),
        ],
      },
      field: 'action',
      fixed: 'right',
      title: '操作',
      width: 150,
      visible: true,
    },
  ];
}

/**
 * 版本历史表格列配置
 * @description 使用函数的形式返回列数据而不是直接export一个Array常量，是为了响应语言切换时重新翻译表头
 * @param onActionClick 表格操作按钮点击事件
 */
export function useVersionColumns(
  onActionClick?: (params: OnActionClickParams<BOMApi.BOMVersion>) => void,
): VxeTableGridOptions<BOMApi.BOMVersion>['columns'] {
  return [
    {
      type: 'checkbox',
      width: 50,
    },
    {
      type: 'seq',
      title: '序',
      width: 60,
      align: 'center',
      visible: true,
    },
    {
      field: 'id',
      title: 'ID',
      width: 80,
    },
    {
      field: 'version',
      title: '版本号',
      width: 100,
      align: 'center',
    },
    {
      field: 'status',
      title: '状态',
      width: 100,
      align: 'center',
      showOverflow: 'tooltip',
      formatter: dictFormatter(DICT_TYPE.BOM_STATUS),
    },
    {
      field: 'is_active',
      title: '是否激活',
      width: 100,
      align: 'center',
      formatter: ({ cellValue }) => (cellValue ? '是' : '否'),
    },
    {
      field: 'creator',
      title: '创建人',
      width: 100,
      align: 'center',
    },
    {
      field: 'create_time',
      title: '创建时间',
      width: 150,
      align: 'center',
    },
    {
      field: 'remark',
      title: '备注',
      width: 150,
      align: 'left',
      showOverflow: 'tooltip',
    },
    {
      align: 'center',
      cellRender: {
        attrs: {
          nameField: 'version',
          nameTitle: 'BOM版本',
          onClick: onActionClick,
        },
        name: 'CellOperation',
        options: [
          op('bom:bom:version:view', 'view'),
          op('bom:bom:version:activate', 'activate'),
          op('bom:bom:version:delete', 'delete'),
        ],
      },
      field: 'action',
      fixed: 'right',
      title: '操作',
      width: 150,
      visible: true,
    },
  ];
}

/**
 * BOM模块配置汇总
 * @description 包含BOM模块所有表单配置、表格列配置、默认值和验证规则
 */
export const bomConfig = {
  // 表单配置函数
  forms: {
    gridForm: useGridFormSchema,
    bomForm: useSchema,
    componentForm: useComponentSchema,
    documentForm: useDocumentSchema,
    versionForm: useVersionSchema,
    alternativeForm: useAlternativeSchema,
    tabbedForm: useTabbedSchema,
  },
  
  // 表格列配置函数
  columns: {
    bomTable: useColumns,
    componentTable: useComponentColumns,
    alternativeTable: useAlternativeColumns,
    documentTable: useDocumentColumns,
    versionTable: useVersionColumns,
  },
  
  // 表单默认值
  defaultValues: {
    bomForm: bomFormDefaultValues,
    componentForm: componentFormDefaultValues,
    alternativeForm: alternativeFormDefaultValues,
    documentForm: documentFormDefaultValues,
    versionForm: versionFormDefaultValues,
  },
  
  // 表单验证规则
  rules: {
    bomForm: bomFormRules,
    componentForm: componentFormRules,
    alternativeForm: alternativeFormRules,
    documentForm: documentFormRules,
    versionForm: versionFormRules,
  },
  
  // 字典类型
  dictTypes: {
    BOM_TYPE: DICT_TYPE.BOM_TYPE,
    BOM_STATUS: DICT_TYPE.BOM_STATUS,
    LIFECYCLE_STATUS: DICT_TYPE.LIFECYCLE_STATUS,
    MATERIAL_TYPE: DICT_TYPE.MATERIAL_TYPE,
    APPROVAL_STATUS: DICT_TYPE.APPROVAL_STATUS,
    CHANGE_TYPE: DICT_TYPE.CHANGE_TYPE,
    DOCUMENT_TYPE: DICT_TYPE.DOCUMENT_TYPE,
  },
  
  // 单位选项
  unitOptions: UNIT_OPTIONS,
};
